<?php defined('SYSPATH') OR die('No direct access allowed.');
/**
 * Librería para request de curl con cache
 * @author aveliz
 */
class Curl_Cache_Core {
	private $url;
	private $ttl;
	private $cache_path;
	private $timeout 	= 15;
	
	public function __construct($url, $ttl = 86400)
	{
		$this->url = $url;
		$this->ttl = $ttl;
	}
	
	public static function factory($url, $ttl = FALSE)
	{
		return new Curl_Cache();
	}

	public function setCachePath($cache_path)
	{
		$this->cache_path = $cache_path;
	}
	
	public function setTtl($ttl)
	{
		$this->ttl = $ttl;
	}
	
	public function getData()
	{
		$cache_file   = sprintf('%s/%08X.cc', $this->cache_path, crc32($this->url));
		$cache_exists = is_readable($cache_file);
		
		if ( $this->ttl && $cache_exists && ( filemtime($cache_file) > (time() - $this->ttl) ) ) {
			return file_get_contents($cache_file);
		}
		touch($cache_file);
		clearstatcache();

		$c = curl_init();
		curl_setopt($c, CURLOPT_URL, $this->url);
		curl_setopt($c, CURLOPT_TIMEOUT, $this->timeout);
		curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($c, CURLOPT_USERAGENT, 'edoFetcher/0.9  (http://example.com/; bob@example.com)');
		
		if ($cache_exists) {
			curl_setopt($c, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
			curl_setopt($c, CURLOPT_TIMEVALUE, filemtime($cache_file));
		}

		$content = curl_exec($c);
		$status = curl_getinfo($c, CURLINFO_HTTP_CODE);
		
		if ($cache_exists && ($status == 304)) { 
			return file_get_contents($cache_file);
		}

		if ($status != 200) { 
			throw new Exception(sprintf('Unexpected HTTP return code %d', $status));
		}

		file_put_contents($cache_file, $content);
		chmod($cache_file, 0644);
		return $content;
	}
}